<template>
    <el-form :model="formData" label-width="150px">
        <el-form-item label="行为来源">
            <el-checkbox-group v-model="formData.shop_source" @change="changeSource">
                <el-checkbox :label="-1">不限</el-checkbox>
                <el-checkbox v-for="(item, index) in storeres" :key="index" :label="item.id">
                    {{ item.name }}
                </el-checkbox>
            </el-checkbox-group>
        </el-form-item>
        <el-form-item label="访问来源">
            <el-checkbox-group v-model="formData.visit_source" @change="changVisit">
                <el-checkbox :label="-1">不限</el-checkbox>
                <el-checkbox v-for="(item, index) in visitList" :key="index" :label="item.id">
                    {{ item.name }}
                </el-checkbox>
            </el-checkbox-group>
        </el-form-item>
        <el-form-item label="用户行为">
            <el-checkbox-group v-model="formData.behaviour" @change="changStatusBehaviour">
                <el-checkbox :label="-1">不限</el-checkbox>
                <el-checkbox v-for="(item, index) in custList" :key="index" :label="item.id">
                    {{ item.name }}
                </el-checkbox>
            </el-checkbox-group>
        </el-form-item>
        <el-form-item class="form-item" label="行为时间">
            <el-button :class="fllowTime == 3 ? 'time-color' : ''" @click="changeTime(3)">近3天</el-button>
            <el-button :class="fllowTime == 7 ? 'time-color' : ''" @click="changeTime(7)">近7天</el-button>
            <el-button :class="fllowTime == 15 ? 'time-color' : ''" @click="changeTime(15)">近15天</el-button>
            <el-button :class="fllowTime == 30 ? 'time-color' : ''" @click="changeTime(30)">近30天</el-button>
            <el-button :class="fllowTime == -2 ? 'time-color' : ''" @click="changeTime(-2)">近N天</el-button>
            <el-input-number
                v-if="fllowTime == -2"
                v-model.number="behav_day"
                class="right-input"
                :controls="false"
                :precision="0"
                :min="1"
                :max="1000"
                @blur="changeBehavDay"></el-input-number>
            <el-button :class="fllowTime == 0 ? 'time-color' : ''" @click="changeTime(0)">自定义</el-button>
            <el-date-picker
                v-if="showAddTime"
                v-model="formData.behaviour_time"
                type="datetimerange"
                class="right-picker"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 380px; margin-left: 10px; vertical-align: middle"></el-date-picker>
            <el-button :class="fllowTime == -1 ? 'time-color' : ''" class="right-item" @click="changeTime(-1)">
                不限制
            </el-button>
        </el-form-item>
        <div v-if="visit_page">
            <div v-for="(item, index) in pageLists" :key="index">
                <el-form-item :label="item.retail_shop.name + '浏览页面'">
                    <el-checkbox-group v-model="item.page_ids" @change="val => changStatus(val, item, index)">
                        <el-checkbox :label="-1">不限</el-checkbox>
                        <el-checkbox v-for="(item, index) in item.page_list" :key="index" :label="item.id">
                            {{ item.page_name }}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </div>
        </div>
        <div v-if="visit_product">
            <div v-for="(item, index) in pageLists" :key="index">
                <el-form-item :label="item.retail_shop.name + '浏览商品'">
                    <el-radio-group v-model="item.visit_product_type" @change="changeProduct(item)">
                        <el-radio :label="1">不限</el-radio>
                        <el-radio :label="2">指定浏览以下任意一个商品</el-radio>
                        <el-radio :label="3">指定浏览以下所有商品</el-radio>
                    </el-radio-group>
                    <div v-show="item.visit_product_type != 1" class="group-list">
                        <div v-for="(item, index) in item.shopList" :key="index" class="list-item">
                            <img
                                class="del-img"
                                width="16"
                                height="16"
                                src="@/assets/customer/del.png"
                                alt="删除"
                                @click="delShop(item, index)" />
                            <div class="item-img">
                                <img width="36" height="36" style="border-radius: 4px" :src="item.cover" alt="" />
                            </div>
                            <div class="item-tips">
                                <div class="item-title">{{ item.product_name || '--' }}</div>
                            </div>
                        </div>
                    </div>
                    <div v-show="item.visit_product_type != 1">
                        <el-button type="primary" style="margin-bottom: 5px" @click="onOpenUpload(item.retail_shop.id)">
                            选择商品
                        </el-button>
                    </div>
                </el-form-item>
            </div>
        </div>
        <el-form-item label="浏览时长">
            <el-input
                v-model.number="numList.visit_min"
                class="item-input input-left"
                onkeyup="value=value.replace(/[^0-9]/g,'')"
                placeholder="最小值"
                @input="handleNum(1)">
            </el-input>
            ~
            <el-input
                v-model.number="numList.visit_max"
                class="item-input"
                onkeyup="value=value.replace(/[^0-9]/g,'')"
                placeholder="最大值"
                @input="handleNum(2)">
            </el-input>
            S
        </el-form-item>
        <el-form-item class="form-item" label="评论内容">
            <div>
                <el-radio-group v-model="formData.comment_type" @change="changeType">
                    <el-radio :label="1">不限</el-radio>
                    <el-radio :label="2">包含以下任意一个关键词</el-radio>
                </el-radio-group>
                <div>
                    <div>
                        <el-tag
                            v-for="(tag, index) in formData.comment_keywords"
                            :key="index"
                            style="margin-right: 5px"
                            type="warning"
                            closable
                            @close="handleClose(tag)">
                            {{ tag }}
                        </el-tag>
                    </div>
                    <el-input
                        v-show="formData.comment_type == 2"
                        v-model="tagItem"
                        placeholder="输入关键词，回车确认"
                        style="width: 280px"
                        @keyup.enter="submitTag">
                    </el-input>
                </div>
            </div>
        </el-form-item>
    </el-form>
    <ZWMatericalLib ref="ZWMatericalLibRef" @submit="getFiles" />
</template>

<script setup lang="ts">
import { onBeforeUnmount, ref, reactive, watch } from 'vue';
import { getDiffDay } from '@/utils/utils';
import { getDay } from '@/utils/timeCycle';
import { storeList, dictEnum, pageListFun } from '@/api/highMaterial/sourceMaterials';
// import ZWMatericalLib from '@/components/channelNew/ZWMatericalLibNew.vue'
import ZWMatericalLib from '@/components/channelNew/ZWMatericalLib.vue';
import { getSetionId } from '@/utils/utils';
const behav_day = ref(60);
const formData = reactive({
    shop_source: [-1],
    visit_source: [-1],
    behaviour: [-1],
    behaviour_time: [] as any[],
    behaviour_day: 0, //用户行为近n天 0为自定义和不限制 自定义需传behaviour_time不限制传[]
    shop_visit_page: [], //店铺浏览页面
    shop_visit_product: [], //店铺浏览商品
    visit_duration: [], //浏览时长
    comment_type: 1, //评论类型：1 不限，2 包含以下关键词
    comment_keywords: [] //评论关键词
});
const storeres = ref([]); //行为来源
const visitList = ref([]); //访问来源
const custList = ref([]); //客户行为
const shopList = ref([]); //选中的商品
const numList = reactive({
    visit_min: '',
    visit_max: ''
});
const ZWMatericalLibRef = ref(null);
const tagItem = ref();
const stageListOptList = ref([]);
const pageLists = ref([]); //浏览页面列表
const isChat = ref(false);
const showAddTime = ref(false);
const visit_page = ref(false);
const visit_product = ref(false);
const fllowTime = ref(-1);
const props = defineProps(['cust_property_behaviour']);
const shopId = ref<string>('');
//校验
const handleNum = (val: number) => {
    formData.visit_duration = [numList.visit_min, numList.visit_max];
    if (numList.visit_min === '' && numList.visit_max === '') {
        formData.visit_duration = [];
    }
};
//获取关键词
const submitTag = () => {
    if (tagItem.value) {
        formData.comment_keywords.push(tagItem.value);
        tagItem.value = '';
    }
};
//删除标签
const handleClose = (tag: string) => {
    formData.comment_keywords.splice(formData.comment_keywords.indexOf(tag), 1);
};
//获取店铺列表（行为来源）
const storeListFun = () => {
    storeList({ source: [1, 2, 4], status: 1 }).then((res: any) => {
        storeres.value = res;
    });
};
storeListFun();
//获取访问来源
const getDictEnum = () => {
    dictEnum({ dict_id: 6 }).then((res: any) => {
        visitList.value = res;
    });
};
getDictEnum();
//获取用户行为
const getCustEnum = () => {
    dictEnum({ dict_id: 3 }).then((res: any) => {
        custList.value = res;
    });
};
getCustEnum();
//获取店铺页面列表
const getPageLists = (val: any) => {
    pageListFun({ shop_id: val }).then((res: any) => {
        pageLists.value = res.map((item, index) => {
            if (pageLists.value.some(ite => ite.retail_shop?.id == item.retail_shop?.id)) {
                return pageLists.value.find(ite => ite.retail_shop?.id == item.retail_shop?.id);
            } else {
                item.page_ids = formData.shop_visit_page[index]?.page_ids || [];
                item.product_ids = formData.shop_visit_product[index]?.product_ids.map(v => {
                    return v.id;
                });
                item.shopList = formData.shop_visit_product[index]?.product_ids.map(v => ({
                    product_name: v.product_name,
                    cover: v.cover,
                    id: v.id
                }));
                item.ischeck = false;
                item.visit_product_type = formData.shop_visit_product[index]?.visit_product_type || 1;
                return item;
            }
        });
    });
};
// 打开上传
const onOpenUpload = (num: string) => {
    shopId.value = num;
    const showTabs = ['99'];
    ZWMatericalLibRef.value.showTabs = showTabs;
    ZWMatericalLibRef.value.baseId = 99; //打开对应的基础素材
    ZWMatericalLibRef.value.storesIds = [num];
    ZWMatericalLibRef.value.infinite = true;
    ZWMatericalLibRef.value.isGoodsOnly = true;
    ZWMatericalLibRef.value.materVisible = true;
};
//获取商品列表
const getFiles = (res: any) => {
    pageLists.value.some(item => {
        if (item?.retail_shop?.id == shopId.value) {
            item.shopList = res.data;
            const product_ids = [];
            res.data.forEach((item: any) => {
                product_ids.push(item.id);
            });
            formData.shop_visit_product.forEach((item: any, index: any) => {
                if (item.retail_shop_id == shopId.value) {
                    formData.shop_visit_product[index] = {
                        retail_shop_id: shopId.value,
                        visit_product_type: item.visit_product_type,
                        product_ids: product_ids
                    };
                }
            });
            return true;
        } else {
            return false;
        }
    });
};
//删除商品列表
const delShop = (data: any) => {
    pageLists.value.forEach(item => {
        item.shopList = item.shopList.filter((item: any) => {
            return item.id != data.id;
        });
        const product_ids = [];
        item.shopList.forEach((item: any) => {
            product_ids.push(item.id);
        });
        formData.shop_visit_product = [
            {
                retail_shop_id: item?.retail_shop?.id,
                visit_product_type: item.visit_product_type,
                product_ids: product_ids
            }
        ];
    });
};
//切换最后跟进时间or上次聊天时间
const changeTime = (type: any, val: any) => {
    fllowTime.value = type;
    showAddTime.value = false;
    if (type != 0) {
        formData.behaviour_time = [];
    }
    switch (type) {
        case 3:
            return (formData.behaviour_day = 3);
        case 7:
            return (formData.behaviour_day = 7);
        case 15:
            return (formData.behaviour_day = 15);
        case 30:
            return (formData.behaviour_day = 30);
        case 0:
            formData.behaviour_day = 0;
            return (showAddTime.value = true);
        case -1:
            return (formData.behaviour_day = 0);
        case -2:
            return (formData.behaviour_day = behav_day.value);
    }
};
//切换浏览页
const changStatus = (val: any, item, ind) => {
    const index = val[val.length - 1];
    if (index == -1) {
        item.page_ids = [-1];
    } else {
        item.page_ids = val.filter((item: any) => {
            return item != -1;
        });
    }
    if (formData.shop_visit_page.length > 0) {
        formData.shop_visit_page = formData.shop_visit_page.filter((jtem: any) => {
            return jtem.retail_shop_id != item.retail_shop.id;
        });
        formData.shop_visit_page.push({ retail_shop_id: item.retail_shop.id, page_ids: item.page_ids });
    } else {
        formData.shop_visit_page.push({ retail_shop_id: item.retail_shop.id, page_ids: item.page_ids });
    }
};
//切换行为来源
const changeSource = (val: any) => {
    if (val.length == 0) {
        formData.shop_source = [-1];
    } else {
        const index = val[val.length - 1];
        if (index == -1) {
            formData.shop_source = [-1];
        } else {
            formData.shop_source = val.filter((item: any) => {
                return item != -1;
            });
        }
        if (formData.shop_source.length > 0) getPageLists(formData.shop_source);
    }
};
//切换用户行为
const changStatusBehaviour = (val: any) => {
    if (val.length == 0) {
        formData.behaviour = [-1];
    } else {
        const index = val[val.length - 1];
        if (index == -1) {
            formData.behaviour = [-1];
        } else {
            formData.behaviour = val.filter((item: any) => {
                return item != -1;
            });
        }
        if (formData.behaviour.length > 0) {
            if (formData.behaviour.includes('1')) {
                visit_page.value = true;
            } else {
                visit_page.value = false;
            }
            if (
                formData.behaviour.includes('2') ||
                formData.behaviour.includes('5') ||
                formData.behaviour.includes('6') ||
                formData.behaviour.includes('7') ||
                formData.behaviour.includes('9') ||
                formData.behaviour.includes('10')
            ) {
                visit_product.value = true;
            } else {
                visit_product.value = false;
            }
        } else {
            visit_page.value = false;
            visit_product.value = false;
        }
        if (!visit_product.value) {
            formData.shop_visit_page = [];
            pageLists.value.forEach((item: any) => {
                item.page_ids = [];
            });
        }
        if (!visit_product.value) {
            formData.shop_visit_product = [];
            pageLists.value.forEach((item: any) => {
                item.visit_product_type = 1;
                item.product_ids = [];
                item.shopList = [];
            });
        }
        if (formData.behaviour.length > 0) {
            pageLists.value.forEach((item: any) => {
                formData.shop_source.forEach((jtem: any) => {
                    if (item?.retail_shop?.id == jtem) {
                        if (visit_product.value) {
                            formData.shop_visit_product.push({
                                retail_shop_id: item?.retail_shop?.id,
                                visit_product_type: 1,
                                product_ids: []
                            });
                        }
                    } else {
                        return false;
                    }
                });
            });
        }
    }
};
//切换浏览商品
const changeProduct = (val: any) => {
    pageLists.value.some((item: any, index: any) => {
        if (item?.retail_shop?.id == val.retail_shop.id) {
            if (val.visit_product_type == 1) {
                item.visit_product_type = val.visit_product_type;
                item.product_ids = [];
                item.shopList = [];
                formData.shop_visit_product[index] = {
                    retail_shop_id: item?.retail_shop?.id,
                    visit_product_type: item.visit_product_type,
                    product_ids: []
                };
            } else {
                if (val.shopList) {
                    item.shopList = val.shopList;
                    const product_ids = [];
                    val.shopList.forEach((item: any) => {
                        product_ids.push(item.id);
                    });
                    formData.shop_visit_product[index] = {
                        retail_shop_id: item?.retail_shop?.id,
                        visit_product_type: item.visit_product_type,
                        product_ids: product_ids
                    };
                    return true;
                }
            }
        } else {
            return false;
        }
    });
};
//切换访问来源
const changVisit = (val: any) => {
    if (val.length == 0) {
        formData.visit_source = [-1];
    } else {
        const index = val[val.length - 1];
        if (index == -1) {
            formData.visit_source = [-1];
        } else {
            formData.visit_source = val.filter((item: any) => {
                return item != -1;
            });
        }
    }
};
//切换评论内容
const changeType = () => {
    if (formData.comment_type == 1) {
        formData.comment_keywords = [];
    }
};
//处理返参
const filFormat = (val: any) => {
    if (val == null) {
        return '';
    } else {
        return val;
    }
};
// 行为时间切换近N天
const changeBehavDay = () => {
    formData.behaviour_day = behav_day.value || 60;
    behav_day.value = behav_day.value || 60;
};
const updateData = (val: any) => {
    formData.shop_source = val.shop_source;
    formData.visit_source = val.visit_source;
    formData.behaviour_time = val.behaviour_time;
    formData.behaviour = val.behaviour;
    formData.comment_type = val.comment_type;
    formData.comment_keywords = val.comment_keywords;
    formData.visit_duration = val.visit_duration;
    numList.visit_min = filFormat(val.visit_duration[0]);
    numList.visit_max = filFormat(val.visit_duration[1]);
    formData.shop_visit_page = val.shop_visit_page;
    formData.shop_visit_product = val.shop_visit_product;
    formData.behaviour_day = val.behaviour_day;
    if (val.behaviour_time && val.behaviour_time.length > 0) {
        fllowTime.value = 0;
        showAddTime.value = true;
    } else {
        if (val.behaviour_day == 0) {
            fllowTime.value = -1;
        } else {
            if ([3, 7, 15, 30].includes(val.behaviour_day)) {
                fllowTime.value = val.behaviour_day;
            } else {
                fllowTime.value = -2;
                behav_day.value = val.behaviour_day;
            }
        }
    }
    if (val.shop_source.length > 0) getPageLists(val.shop_source);
    if (val.behaviour.length > 0) changStatusBehaviour(val.behaviour);
};
watch(
    () => props.cust_property_behaviour,
    val => {
        if (val && val.id) {
            updateData(val);
        }
    }
);
defineExpose({
    formData,
    fllowTime
});
</script>
<style scoped lang="scss">
.form-item {
    margin: 10px 0;

    .right-item {
        margin-left: 10px;
    }

    .time-color {
        background-color: #ff6b00;
        color: #fff;
    }
}

.item-input {
    width: 90px;
    margin: 5px;
}

.input-left {
    margin-left: 0;
}

.group-list {
    display: flex;
    flex-wrap: wrap;

    .list-item {
        width: 227px;
        height: 48px;
        display: flex;
        border: 1px solid #ffc69e;
        line-height: 20px;
        position: relative;
        margin: 0 16px 16px 0;

        .del-img {
            position: absolute;
            right: -6px;
            top: -6px;
        }

        .item-img {
            margin: 6px 10px 6px 6px;
        }

        .item-tips {
            margin: 4px 0;

            .item-title {
                color: #33302d;
                font-size: 14px;
                width: 100%;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                word-break: break-all;
                -webkit-line-clamp: 2;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }
    }
}

.right-input {
    width: 90px;
    margin: 0 12px;
}

:deep input::-webkit-outer-spin-button,
:deep input::-webkit-inner-spin-button {
    appearance: none;
}

:deep input[type='number'] {
    appearance: textfield;
}
</style>
